<?php

namespace Acme\DomotiqueBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

use Acme\DomotiqueBundle\Entity\ArduinoConfig;

class ApiController extends Controller
{
	/**
	 * Captures
	 */
    public function feedAction()
    {
        return new Response(json_encode(array("response_code" => "ok")));
    }

    /**
     * Renvoi la configuration à appliquer 
     */
    public function getAction()
    {
    	$config = $this->getDoctrine()
    					->getRepository('DomotiqueBundle:ArduinoConfig')
    					->findAll();
    	$response = "";
    	foreach($config as $conf){
    		$response .= $conf->getPinId().":".$conf->getValue()."\n";
    	}
    	return new Response($response);
    }

    /**
     * Set
     * @param $pin
     * @param $value
     */
    public function setAction($pin, $value)
    {
		$em = $this->getDoctrine()->getManager();

		if($pin < 1 || $pin > 14 ){
			return new Response("error");
		}
		if($value < 0 || $value > 255) {
			return new Response("error");
		}


		$config = $this->getDoctrine()
	        ->getRepository('DomotiqueBundle:ArduinoConfig')
	        ->find($pin);
	    if(is_null($config)){
	    	$config = new ArduinoConfig();
	    	$config->setPinId($pin);
	    }
		$config->setValue($value);
		$em->persist($config);
		$em->flush();

    	return new Response("ok");
    }
}